//
//  EditQuickCardController.m
//  QRMaster
//
//  Created by myApple on 16/5/30.
//  Copyright © 2016年 myApple. All rights reserved.
//

#import "EditQuickCardController.h"
#import "AddAndEditQuickRoomView.h"
#import "QuickCardChooseRoomController.h"
#import "CutOutImageController.h"
#import "UIImageView+WebCache.h"
#import "QuickCardProcess.h"

@interface EditQuickCardController ()<AddAndEditQuickRoomViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIActionSheetDelegate,UIAlertViewDelegate>
{
    UIImageView * submitImageView;
    UILabel * submitLabel;
    AddAndEditQuickRoomView * quickRoomView;
    QuickCardModel * originModel;
    UINavigationController * myNavigationController;
    NSData * imageData;
    BOOL imageChangeFlag;
    QuickCardProcess * dataProcess;
}

@end

@implementation EditQuickCardController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = NSLocalizedString(@"quickCardInfo", @"快捷房卡信息");
    imageChangeFlag = NO;
    self.view.backgroundColor = UIColorFromRGB(0xebebeb);
    dataProcess = [[QuickCardProcess alloc]init];
    [self prepareNavView];
    [self prepareView];
    // Do any additional setup after loading the view.
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    submitImageView.hidden = NO;
     [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:NO];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    submitImageView.hidden = YES;
}

-(void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    myNavigationController = navigationController;
}

-(void)setModel:(QuickCardModel *)model
{
    _model = model;
    originModel = model;
}


#pragma mark - prepareView
-(void)prepareNavView
{
    submitImageView = [[UIImageView alloc]initWithFrame:CGRectMake(UI_SCREEN_WIDTH - 66, 2, 50, 40)];
    submitImageView.userInteractionEnabled = NO;
    UITapGestureRecognizer * submitTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(submit)];
    [submitImageView addGestureRecognizer:submitTap];
    [self.navigationController.navigationBar addSubview:submitImageView];
    
    submitLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 10, 50, 20)];
    submitLabel.text = NSLocalizedString(@"authenSubmit",@"完成");
    submitLabel.textColor = UIColorFromRGBAndA(0x7dc234, 0.5);
    submitLabel.font = [UIFont systemFontOfSize:15.0];
    submitLabel.textAlignment = NSTextAlignmentRight;
    [submitImageView addSubview:submitLabel];
}

-(void)prepareView
{
    quickRoomView = [[AddAndEditQuickRoomView alloc]initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, UI_SCREEN_HEIGHT)];
    quickRoomView.delegate = self;
    quickRoomView.model = _model;
    [quickRoomView.roomImgView sd_setImageWithURL:[NSURL URLWithString:_model.imageURL]];
    [self.view addSubview:quickRoomView];
}

#pragma mark - 添加收藏房卡的代理方法
-(void)AddAndEditQuickRoomViewAddRoom
{
    QuickCardChooseRoomController * qccrc = [[QuickCardChooseRoomController alloc]init];
    __weak EditQuickCardController * weakSelf = self;
    qccrc.roomId = originModel.roomId;
    qccrc.cardInfoBlock = ^(CardInfoModel * model)
    {
        originModel.roomName = model.roomName;
        originModel.roomId = model.roomId;
        originModel.buildingName = model.bulidingName;
        originModel.floorName  = model.floorName;
        originModel.communityId = [QRSingleton sharedQRSingleton].communityId;
        originModel.communityName = [QRSingleton sharedQRSingleton].communityName;
        quickRoomView.model = originModel;
        [weakSelf judgeChange];
    };
    [self.navigationController pushViewController:qccrc animated:YES];
}

-(void)AddAndEditQuickRoomViewChangeImage
{
    [self getFromcamreOrPhoto];
}

-(void)AddAndEditQuickRoomViewChangeName:(NSString *)name
{
    originModel.customerName = name;
    [self judgeChange];
}

#pragma mark ---------- 弹出选择框（照片还是拍摄）
-(void)getFromcamreOrPhoto
{
    UIActionSheet * sheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:NSLocalizedString(@"alterCancel",@"取消")destructiveButtonTitle:NSLocalizedString(@"takePhoto", @"拍照") otherButtonTitles:NSLocalizedString(@"getPhotoFromAlbum", @"从相册中选择") ,nil];
    [sheet showInView:self.view];
}

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        [self getImageFromCamera];
    }
    else if (buttonIndex == 1)
    {
        [self getImageFromPhoto];
    }
}

#pragma mark ---拍照
-(void)getImageFromCamera
{
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    UIImagePickerController * picker = [[UIImagePickerController alloc]init];
    picker.delegate = self;
    picker.allowsEditing = YES;
    picker.sourceType = sourceType;
    [self presentViewController:picker animated:YES completion:nil];
}

#pragma mark --从相册中获取

-(void)getImageFromPhoto
{
    UIImagePickerController *pickerImage = [[UIImagePickerController alloc] init];
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        pickerImage.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        //pickerImage.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
        pickerImage.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:pickerImage.sourceType];
        
    }
    pickerImage.delegate = self;
    pickerImage.allowsEditing = NO;
    [self presentViewController:pickerImage animated:YES completion:nil];
    
}

#pragma mark -- 选择照片或者照相完后触发的方法
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage * image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
    //    [picker dismissViewControllerAnimated:YES completion:nil];
    if (picker.sourceType == UIImagePickerControllerSourceTypePhotoLibrary) {
        CutOutImageController * coic = [[CutOutImageController alloc]init];
        coic.selectImage = image;
        coic.imgBlock = ^(UIImage * selectImg)
        {
            imageChangeFlag = YES;
            quickRoomView.roomImgView.image = selectImg;
            [picker dismissViewControllerAnimated:YES completion:nil];
        };
        [myNavigationController pushViewController:coic animated:YES];
        
    }
    else
    {
        imageChangeFlag = YES;
        quickRoomView.roomImgView.image = image;
        [picker dismissViewControllerAnimated:YES completion:nil];
    }
    [self judgeChange];
}

-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - 修改收藏
-(void)submit
{
    if (![self checkinInput]) {
        return ;
    }
    if ([self IsHaveNetwork]) {
        return;
    }
    __weak EditQuickCardController * weakSelf = self;
    NSMutableDictionary * postDict = [[NSMutableDictionary alloc]init];
    [postDict setValue:originModel.communityId forKey:@"communityId"];
    [postDict setValue:UID forKey:@"id"];
    [postDict setValue:TOKEN forKey:@"token"];
    [postDict setValue:originModel.roomId forKey:@"roomId"];
    if (![originModel.customerName isEqualToString:@""]) {
        [postDict setValue:originModel.customerName forKey:@"name"];
    }
    [postDict setValue:originModel.collectId forKey:@"collectId"];
    if (!imageChangeFlag) {
        imageData = nil;
    }
    [dataProcess eidtCollectionCard:postDict file:imageData block:^(NSString *info, NSString *errorInfo) {
        if (info) {
            [weakSelf.navigationController popViewControllerAnimated:YES];
        }
        else
        {
            [PromptInfoView showMessage:errorInfo superView:weakSelf.view];
        }
    }];

}


#pragma mark - 判断是否有改变
-(void)judgeChange
{
    if ((originModel.customerName != _model.customerName || imageChangeFlag || [originModel.roomId isEqualToString:_model.roomId]) && (originModel.roomId != nil) ) {
        submitImageView.userInteractionEnabled = YES;
        submitLabel.textColor = UIColorFromRGBAndA(0x7dc234, 1);
    }
    else
    {
        submitImageView.userInteractionEnabled = NO;
        submitLabel.textColor = UIColorFromRGBAndA(0x7dc234, 0.5);
    }
}

#pragma mark --------- 检查输入
-(BOOL)checkinInput
{
    if (originModel.customerName.length > 20) {
        [PromptInfoView showMessage:NSLocalizedString(@"房卡名称长度不大于20", @"名称长度不大于20") superView:self.view];
        return NO;
    }
    imageData = UIImageJPEGRepresentation(quickRoomView.roomImgView.image, 0.1);
    if (imageData == nil) {
        return YES;
    }
    long imageSize = [imageData length] / 1024;
    if (imageSize > 3 * 1024) {
        [PromptInfoView showMessage:NSLocalizedString(@"imageThan", @"上传图片不能大于3M") superView:self.view];
        return NO;
    }
    return YES;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
